let express = require("express");

const { render } = require("../tool/read")

let Router = express.Router();

const { searchOne, searchMany, count } = require("../tool/db")

// /grade
Router.get("/", async function (req, res) {
    res.end("grade")
})

Router.get("/list", async function (req, res) {
    var sql = `select * frm grade`;
    var obj = {}
    searchMany(sql).then(data => {
        console.log(data);
        obj.status = true;
        obj.msg = "ok";
        obj.list = data;
        res.json(obj);
    }).catch(err => {
        obj.status = false;
        obj.msg = err.sqlMessage;
        obj.sql = err.sql;
        res.json(obj);
    })
})

Router.get("/searchGradeOrderLimit", async function (req, res) {
    console.log(req.query);
    // var { key = "", orderCol = "id", orderType = "asc", pageIndex = 1, showNum = 5 } = req.query;

    var { key, orderCol, orderType, pageIndex, showNum } = req.query;

    var obj = {};
    try {

        if ((key || key == "") && orderCol && orderType && pageIndex && showNum) {

            // pageIndex 超出临界值 (1-maxPage)   => 做限制
            var sql = `select id,name,class,chinese,math,english,chinese+math+english as total from grade where name like '%${key}%' order by ${orderCol} ${orderType}`
            var total = await count(sql)
            console.log(total);
            var maxPage = Math.ceil(total / showNum);

            if (pageIndex > maxPage) pageIndex = maxPage;
            if (pageIndex < 1) pageIndex = 1;

            var sql = `select id,name,class,chinese,math,english,chinese+math+english as total from grade where name like '%${key}%' order by ${orderCol} ${orderType} limit ${(pageIndex - 1) * showNum},${showNum}`;
            var obj = {}
            var data = await searchMany(sql)


            obj.status = true;
            obj.msg = "ok";
            obj.total = total;
            obj.currentIndex = pageIndex;
            obj.maxPage = maxPage;
            obj.list = data;

        } else {
            obj.status = false;
            obj.msg = "请传入完整参数";
        }
    } catch (err) {
        console.log(err);
        obj.status = false;
        obj.msg = err;

    }

    res.json(obj);
})


module.exports = Router;